// Author	: damphat@gmail.com
// Created	: 01/12/2008

#pragma once

#include <winsock2.h>
#include <stdio.h>
#include <tchar.h>

#ifdef _MSC_VER
// wince not support #include <ws2ipdef.h>
#else
#endif

#define NET_BEGIN namespace Net {
#define NET_END }
#define NET_USING using namespace Net;

#define CHECK_ARG_RANGE_PORT(port)\
	CHECK_ARG_RANGE(port, 0, USHRT_MAX)

// Use for all winsock2 APIs except WSAStartup
#define CHECK_WINSOCK(condition)\
	if(!(condition)) {\
		SocketException e(WSAGetLastError(), __FUNCTION__);\
		_tprintf(_T("%s"), e.ToString().C_STR());\
		throw e;\
	}

// Use for WSAStartup only
#define CHECK_WINSOCK_WSASTARTUP(condition, rtnOfWSAStartup)\
	if(!(condition)) {\
		SocketException e(rtnOfWSAStartup, __FUNCTION__);\
		throw e;\
	}

#include "SocketException.h"


NET_BEGIN

static WSADATA wsaData;
static void SocketStartup() {
	static bool started = false;
	if(!started) {
		int wsaError = WSAStartup( MAKEWORD(2,2), &wsaData );
		// note: don't use WSAGetLastError() if WSAStartup failed
		CHECK_WINSOCK_WSASTARTUP(wsaError == NO_ERROR, wsaError);
	}
	started = true;
}

static void SocketCleanup() {
	int ret = WSACleanup();
	CHECK_WINSOCK(ret != 0);
}

NET_END
